package com.hsmpay.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


public class UrlUtil {
	static Logger log = Logger.getLogger(UrlUtil.class);
	public static String getDecoder(String string,String coding){
		String ret="";
		try {
			ret=URLDecoder.decode(string, coding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
	public static String getEncoder(String string,String coding){
		String ret="";
		try {
			ret=URLEncoder.encode(string, coding);
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		}
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	public static String httpClientUtils(String url,Map<String,String> map)throws Exception {
		
		HttpClient httpClient;
        PostMethod postMethod = null;
        String reStr = "";
        try {
            httpClient = new HttpClient();
            postMethod = new PostMethod(url);
            postMethod.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
            Iterator<?> it=map.entrySet().iterator();
            NameValuePair[] postData = new NameValuePair[map.entrySet().size()];
            String str="";
            int n=0;
            while(it.hasNext())
            {
            	Entry<String, String> entry = (Entry<String, String>) it.next();
            	String key=entry.getKey().toString();
            	String value=entry.getValue().toString();
	            postData[n]=new NameValuePair(key,value);
	            str+="&"+key+"="+value;
	            n++;
            }
            System.out.println("请求参数为:");
            System.out.println(url+"?"+str);
            postMethod.addParameters(postData);
            httpClient.executeMethod(postMethod);
            reStr = postMethod.getResponseBodyAsString();
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != postMethod) {
            	postMethod.releaseConnection();
            }
        }
        //WriteFile.writelogfile("调用接口,返回:"+reStr,LogFloderName);
        System.out.println("调用接口,返回:"+reStr);
        return reStr;
    }
	public static String httpClientUtils(String content) {
		
		String url="http://58.246.136.11:8008/acqPosPlatform/posDeal!deal.ac";
		HttpClient httpClient;
        PostMethod postMethod = null;
        String reStr = null;
        try {
            httpClient = new HttpClient();
            postMethod = new PostMethod(url);
            postMethod.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
            NameValuePair[] postData = new NameValuePair[2];
            postData[0]=new NameValuePair("xml",content);
            postMethod.addParameters(postData);
            
            httpClient.executeMethod(postMethod);
            reStr = postMethod.getResponseBodyAsString();
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != postMethod) {
            	postMethod.releaseConnection();
            }
        }
        return reStr;
    }
	public static String httpClientUtils2(String XML,String _url) throws Exception{
		//String _url= Qian48Constant._url;//"http://localhost/wanjx/back/loginFormAjax.action";//
		String Method="POST";
		String xmlString=XML;
		byte[] xmlData=xmlString.getBytes();
		try {
			xmlData = xmlString.getBytes("UTF-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String urlStr = _url;
		BufferedReader rd =null;
		String msg="";
		System.out.println("请求URL:" + urlStr);
		log.warn("请求参数:" + XML);
		HttpURLConnection urlCon = null;
		try {
			URL url = new URL(urlStr);
			urlCon = (HttpURLConnection) url.openConnection();
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setUseCaches(false);
			urlCon.setRequestMethod(Method);
			urlCon.setConnectTimeout(180000);
			urlCon.setReadTimeout(180000);
			//System.setProperty("sun.net.client.defaultConnectTimeout", "120000");
			//System.setProperty("sun.net.client.defaultReadTimeout", "120000");
			urlCon.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
			urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
			DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
			printout.write(xmlData);
			printout.flush();
			printout.close();
			log.warn("数据发送完成,等待响应...");
			rd = new BufferedReader(new InputStreamReader(urlCon.getInputStream(),"utf-8"));  
			String inputLine;
			while ((inputLine = rd.readLine()) != null)
				msg+=inputLine;
			log.warn("响应数据为:"+msg);
			rd.close();				
		}catch (Exception e) {
			//e.printStackTrace();
			throw e;
		}finally{
			urlCon.disconnect();
		}
		return msg;
	}
	
	public static String httpClientUtils3(String _url,String XML){
		String Method="POST";
		String xmlString=XML;
		byte[] xmlData=xmlString.getBytes();
		try {
			xmlData = xmlString.getBytes();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String urlStr = _url;
		BufferedReader rd =null;
		String msg="";
		System.out.println("请求URL:" + urlStr);
		System.out.println("请求参数:" + XML);
		int ResponseCode=0;
		String ResponseMessage="";
		try {
			URL url = new URL(urlStr);
			HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setUseCaches(false);
			urlCon.setRequestMethod(Method);
			urlCon.setConnectTimeout(30000);
			urlCon.setReadTimeout(30000);

			urlCon.setRequestProperty("Content-Type", "application/x-fox");
			urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
			DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
			printout.write(xmlData);
			printout.flush();
			printout.close();
			System.out.println("数据发送完成,等待响应...");
			ResponseCode=urlCon.getResponseCode();
			if(ResponseCode==200)
			{
				rd = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));  
			}else{
				rd = new BufferedReader(new InputStreamReader(urlCon.getErrorStream()));
			}
			String inputLine;
			while ((inputLine = rd.readLine()) != null)
				msg+=inputLine;
			System.out.println("响应数据为:"+msg);
			rd.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseCode+","+ResponseMessage+"||"+msg;
	}
	
	
	public static String getDomain(HttpServletRequest request) {
		try {

			String url = request.getHeader("Referer");
			url = url.replaceAll("http://", "");

			int index = url.indexOf("/");

			if (index != -1)
				url = url.substring(0, index);
			return "http://"+url;
		} catch (Exception e) {
			return null;
		}
	}
	
	public static void main(String[] args) {		
		//String ret=UrlUtil.httpClientUtils2("<?xml version=\"1.0\" encoding=\"UTF-8\"?><bppos application=\"AccountRegist.Req\" version=\"1.0.0\" sendTime ='20130821153523' sendSeqId ='153523'><terminalId>1</terminalId><merchantName>2</merchantName><legalManName>3</legalManName><legalManIdcard>4</legalManIdcard><mobileNum></mobileNum><personalMerRegNo></personalMerRegNo><taxNo></taxNo><settleAccount>5</settleAccount><settleAccountNo>6</settleAccountNo><settleAgency></settleAgency><occNo></occNo><accountPwd>7</accountPwd><dynamicKeyData>8</dynamicKeyData><terminalInFo></terminalInFo><mac>9</mac></bppos>");
//		String ret = null;
//		try {
//			ret = UrlUtil.httpClientUtils2("");
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		log.error("****"+ret);
	}
}
